package l1j.opqlo.NewSystem.LABA;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.server.DatabaseFactory;
import l1j.server.server.utils.SQLUtil;



public class LabaTable {

	private static Logger _log = Logger.getLogger(LabaTable.class.getName());

	private static LabaTable _instance;

	public static LabaTable getInstance() {
		if (_instance == null) {
			_instance = new LabaTable();
		}
		return _instance;
	}
	private LabaTable() {

		Connection con = null;
		PreparedStatement pstm = null;
		ResultSet rs = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("SELECT * FROM z_opqlo_laba ORDER BY 場次");
			rs = pstm.executeQuery();
			if(rs.last()) {

				final int laba_id = rs.getInt(1);
				System.out.println("目前彩金使用第「"+laba_id+"」筆記錄");
				L1LaBa.setid(laba_id);
				L1LaBa.setround(rs.getInt(2));
				L1LaBa.sethit(rs.getInt(3));
				L1LaBa.setmiss(rs.getInt(4));
				L1LaBa.settotalprize(rs.getInt(5));
				L1LaBa.setWinnerName(rs.getString(6));
			}

		} catch (final SQLException e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(rs);
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}

	public void newLabaData(){
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();
			pstm = con.prepareStatement("INSERT INTO z_opqlo_laba SET 場次=?, 轉數=?, 轉中次數=?, 槓龜次數=?, 累計彩金=?,上一次得主=?");

			if(L1LaBa.getid()<=0){
				pstm.setInt(1, 1);
			}else{
				pstm.setInt(1, L1LaBa.getid());
			}
			pstm.setInt(2, 0);
			pstm.setInt(3, 0);
			pstm.setInt(4, 0);
			pstm.setInt(5, 100);
			pstm.setString(6, L1LaBa.getWinnerName());
			pstm.execute();
		}catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
		L1LaBa.setround(0);
		L1LaBa.sethit(0);
		L1LaBa.setmiss(0);
		L1LaBa.settotalprize(100);
	}
	public void setLabaData(){
		Connection con = null;
		PreparedStatement pstm = null;
		try {
			con = DatabaseFactory.get().getConnection();

			pstm = con.prepareStatement("UPDATE z_opqlo_laba SET 場次=?, 轉數=?, 轉中次數=?, 槓龜次數=?, 累計彩金=?, 上一次得主=? WHERE 場次=?");
			pstm.setInt(7, L1LaBa.getid());
			pstm.setInt(1, L1LaBa.getid());
			pstm.setInt(2, L1LaBa.getround());
			pstm.setInt(3, L1LaBa.gethit());
			pstm.setInt(4, L1LaBa.getmiss());
			pstm.setInt(5, L1LaBa.gettotalprize());
			pstm.setString(6,L1LaBa.getWinnerName());
			pstm.execute();

		}catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);
		} finally {
			SQLUtil.close(pstm);
			SQLUtil.close(con);
		}
	}
}
